#!/usr/bin/python
from google.appengine.ext import db
import model.alert


FIELDS = [
    'comment_id',
    'where_id', 'where_url', 'where_text',
    'topic_id', 'topic_url', 'topic_text',
    'comments_count',
    'entry_content'
]


class Comments(db.Model):
    created = db.DateTimeProperty(auto_now_add=True)
    where_id = db.StringProperty()
    where_url = db.StringProperty()
    where_text = db.StringProperty()
    topic_id = db.StringProperty()
    topic_url = db.StringProperty()
    topic_text = db.StringProperty()
    comments_count = db.IntegerProperty()
    entry_content = db.TextProperty()


def _checkItem(item):
    for i in FIELDS:
        if not item.get(i):
            model.alert.signal('debug',
                               'db/check - not field: %s, item_id: %s' %
                                   (i, item.get('comment_id')))
            return False
    
    comments_count = item.get('comments_count')
    if comments_count:
        item['comments_count'] = int(item.get('comments_count', -1))
    else:
        item['comments_count'] = -1
        model.alert.signal('debug', 'db/check, item_id: %s' % comments_count)
    
    return item
    
def _getCommentsModel(item):
    item = _checkItem(item)
    if item:
        return Comments(
            key_name = item['comment_id'],
            where_id = item['where_id'],
            where_url = item['where_url'],
            where_text = unicode(item['where_text'], 'utf-8'),
            topic_id = item['topic_id'],
            topic_url = item['topic_url'],
            topic_text = unicode(item['topic_text'], 'utf-8'),
            comments_count = item['comments_count'],
            entry_content = unicode(item['entry_content'].strip(), 'utf-8'),
        )
    else:
        None

def get():
    items = []
    for item in Comments.all().order('-created').fetch(50):
        items.append({
            'where_url': item.where_url,
            'where_text': item.where_text,
            'topic_url': item.topic_url,
            'topic_text': item.topic_text,
            'comments_count': item.comments_count,
            'comment_id': item.key().name(),
            'entry_content': item.entry_content,
        })
    return {'items': items}

def add(items):
    puts = []
    for item in items['items']:
        puts.append(_getCommentsModel(item))
    puts = [i for i in puts if i]
    db.put(puts)

def delete(action=''):
    if action == 'all':
        db.delete(Comments.all())
